package com.xiangban.yanglaodajie_admin.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiangban.yanglaodajie_admin.dao.ClassOrActivityMapper;
import com.xiangban.yanglaodajie_admin.dao.ClassOrAvtivityExpandMapper;
import com.xiangban.yanglaodajie_admin.entity.*;
import com.xiangban.yanglaodajie_admin.entity.dto.ClassOrActivityDto;
import com.xiangban.yanglaodajie_admin.entity.dto.ClassScheduleDto;
import com.xiangban.yanglaodajie_admin.entity.res.ApiResultCode;
import com.xiangban.yanglaodajie_admin.exception.BizException;
import com.xiangban.yanglaodajie_admin.utils.CommonUtils;
import com.xiangban.yanglaodajie_admin.utils.PageUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xiangban.yanglaodajie_admin.utils.CommonUtils.BizEmpty;
import static com.xiangban.yanglaodajie_admin.utils.DateUtil.getNowDateTime;
import static com.xiangban.yanglaodajie_admin.utils.DateUtil.getStringTimestamp;

/**
 * @Author Mr. MaYaYun
 * @Data 2021/6/9 16:08
 */
@Service
public class ClassOrActivityService {

    @Autowired
    private ClassOrActivityMapper classOrActivityMapper;
    @Autowired
    private PageUtil pageUtil;
    @Autowired
    private CommonUtils commonUtils;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ClassOrAvtivityExpandMapper expandMapper;

    public PageInfo<ClassOrActivityDto> getClassActivityList(ClassOrActivityDto classOrActivityDto) {//参数：商家id
        if (commonUtils.getShopId(request) == null) {
            throw new BizException(ApiResultCode.FLAG_FAIL_VOUCHER);
        }
        classOrActivityDto.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        PageHelper.startPage(pageUtil.getPage().getPageNum(), pageUtil.getPage().getPageSize());

        //查询课程列表
        List<ClassOrActivityDto> classOrActivities = classOrActivityMapper.selectClassOrActivityList(classOrActivityDto);

        for (ClassOrActivityDto classOrActivity : classOrActivities) {

            //TODO 查询课程老师
            List<ClassOrActivityDto> classOrActivityDtos = classOrActivityMapper.selectTeacher(classOrActivity);
            ArrayList<Object> list = new ArrayList<>();

            for (ClassOrActivityDto orActivityDto : classOrActivityDtos) {
                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("teacher", orActivityDto.getTeacherName());
                map1.put("role", orActivityDto.getRole());
                list.add(map1);
            }
            classOrActivity.setTeacherNames(list);
            //TODO 查询课程上课时间
            List<ClassSchedule> classSchedules = classOrActivityMapper.selectClassSchedule(classOrActivity);
            ArrayList<Object> maps = new ArrayList<>();
            for (ClassSchedule classSchedule : classSchedules) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("classOrActivityId", classSchedule.getClassOrActivityId());
                map.put("week", classSchedule.getWeek());
                String attendTime = classSchedule.getAttendTime();
                JSONArray objects = JSON.parseArray(attendTime);
                map.put("attendTime", objects);
                maps.add(map);
            }
            classOrActivity.setAttendTimes(maps);
            //TODO 获取课程教材
            Map<String, Object> classMaterials = getClassMaterials(classOrActivity.getId());
            if (classMaterials.keySet().size()>0){
                classOrActivity.setClassMaterials(classMaterials);
            }
            //TODO 教学大纲
            List<String> classOutline = getClassOutline(classOrActivity.getId());
            if (classOutline.size() > 0) {
                classOrActivity.setClassOutline(classOutline);
            }
            //TODO 教学进度
            List<Object> classProgress = getClassProgress(classOrActivity.getId());
            if (classProgress.size()>0){
                classOrActivity.setClassProgress(classProgress);
            }



        }
        return new PageInfo<>(classOrActivities);
    }


    public Object classActivityInfo(ClassOrActivity classOrActivity) {

        if (BizEmpty(classOrActivity.getId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(commonUtils.getShopId(request))) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        classOrActivity.setShopId(Integer.parseInt(commonUtils.getShopId(request)));

        //查询课程信息
        ClassOrActivityDto classOrActivityDto = classOrActivityMapper.selectClassOrActivityInfo(classOrActivity);
        //查询课程上课时间
        if (classOrActivityDto != null) {
            List<ClassSchedule> classSchedules = classOrActivityMapper.selectClassSchedule(classOrActivityDto);
            ArrayList<Object> maps = new ArrayList<>();
            if (classSchedules != null && classSchedules.size() > 0) {
                for (ClassSchedule classSchedule : classSchedules) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("week", classSchedule.getWeek());
                    String attendTime = classSchedule.getAttendTime();
                    JSONArray objects = JSON.parseArray(attendTime);
                    map.put("attendTime", objects);
                    maps.add(map);
                }
                classOrActivityDto.setAttendTimes(maps);
            }
            //查询课程老师
            List<ClassOrActivityDto> classOrActivityDtos = classOrActivityMapper.selectTeacher(classOrActivityDto);
            ArrayList<Object> list = new ArrayList<>();
            if (classOrActivityDtos != null && classOrActivityDtos.size() > 0) {
                for (ClassOrActivityDto orActivityDto : classOrActivityDtos) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("teacherId", orActivityDto.getTeacherId());
                    map.put("teacherName", orActivityDto.getTeacherName());
                    list.add(map);
                }
                classOrActivityDto.setTeacherNames(list);
            }
            if (classOrActivityDto.getIsParent() == 1) {
                Integer classPid = classOrActivityDto.getClassPid();
                ClassOrActivity classOrActivity1 = new ClassOrActivity();
                classOrActivity1.setShopId(classOrActivity.getShopId());
                classOrActivity1.setId(classPid);
                ClassOrActivityDto classOrActivityDto1 = classOrActivityMapper.selectClassOrActivityInfo(classOrActivity1);
                if (classOrActivityDto1 != null) {
                    classOrActivityDto.setParentName(classOrActivityDto1.getClassName());
                }
            }
            return classOrActivityDto;
        } else {
            return new ClassOrActivityDto();
        }


    }

    @Transactional
    public void addClassActivity(ClassOrActivity classOrActivity) {//参数：**
        if (commonUtils.getShopId(request) == null) {
            throw new BizException(ApiResultCode.FLAG_FAIL_VOUCHER);
        }
        if (BizEmpty(classOrActivity.getClassAddress())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getClassName())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getLongitude())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getLatitude())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getScope())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getLabel())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getImage())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getInventory())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getClassifyGoodsId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getStartTime())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getEndTime())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getIsSell())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getIsParent())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        classOrActivity.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        classOrActivity.setStatus(1);
        classOrActivityMapper.InsertClassOrActivity(classOrActivity);
    }

    /**
     * 参数：星期、课程、时间
     * 添加上课时间
     **/
    @Transactional
    public void addClassActivityTime(ClassScheduleDto classScheduleDto) throws ParseException {
        if (BizEmpty(commonUtils.getShopId(request))) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classScheduleDto.getClassOrActivityId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classScheduleDto.getWeek())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classScheduleDto.getAttendTimes())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        //查询课程时间是否添加重复
        ClassScheduleDto classScheduleDto1 = classOrActivityMapper.selectClassScheduleInfo(classScheduleDto);
        if (classScheduleDto1 == null) {
            if (classScheduleDto.getAttendTimes().size() > 1) {
                for (int i = 1; i < classScheduleDto.getAttendTimes().size(); i++) {
                    //获取第n次添加时间结束时间 （第一次）
                    Object o = classScheduleDto.getAttendTimes().get(i - 1);
                    long scheduleEndTime = getScheduleEndTime(o);
                    //获取第n+1次添加时间开始时间
                    Object o1 = classScheduleDto.getAttendTimes().get(i);
                    long scheduleStartTime = getScheduleStartTime(o1);
                    //比较第n+1次开始时间和n次得结束时间
                    if (scheduleStartTime <= scheduleEndTime) {
                        throw new BizException(ApiResultCode.NO_LATER_THAN_LAST_TIME);
                    }
                }
            }
            String s = JSON.toJSONString(classScheduleDto.getAttendTimes());
            classScheduleDto.setAttendTime(s);
            classOrActivityMapper.insertClassSchedule(classScheduleDto);
        } else {
            throw new BizException(ApiResultCode.SCHEDULE_EXIST);
        }
    }

    private long getScheduleEndTime(Object o) throws ParseException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map map = objectMapper.convertValue(o, Map.class);
        String end_time = (String) map.get("end_time");
        Date parse = new SimpleDateFormat("HH:mm").parse(end_time);
        long time = parse.getTime();
        return time;
    }

    private long getScheduleStartTime(Object o) throws ParseException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map map = objectMapper.convertValue(o, Map.class);
        String start_time = (String) map.get("start_time");
        Date parse = new SimpleDateFormat("HH:mm").parse(start_time);
        long time = parse.getTime();
        return time;
    }

    /**
     * 获取上课时间详情
     *
     * @param classScheduleDto
     */
    public Object getClassActivityTime(ClassScheduleDto classScheduleDto) {

        if (BizEmpty(classScheduleDto.getWeek())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classScheduleDto.getClassOrActivityId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }

        ClassScheduleDto classScheduleDto1 = classOrActivityMapper.selectClassScheduleInfo(classScheduleDto);
        String attendTime = classScheduleDto1.getAttendTime();
        Object parse = JSON.parse(attendTime);
        classScheduleDto1.setAttendTimes((List<Object>) parse);
        classScheduleDto1.setAttendTime(null);
        return classScheduleDto1;
    }

    /**
     * 修改上课时间
     **/
    public void updateClassActivityTime(ClassScheduleDto classScheduleDto) throws ParseException {
        if (BizEmpty(commonUtils.getShopId(request))) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classScheduleDto.getClassOrActivityId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classScheduleDto.getWeek())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classScheduleDto.getAttendTimes())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classScheduleDto.getSourceWeek())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        //查询课程时间是否修改重复
        ClassScheduleDto classScheduleDto1 = classOrActivityMapper.selectClassScheduleInfo(classScheduleDto);
        //课程时间不重复
        if (classScheduleDto1 == null) {
            if (classScheduleDto.getAttendTimes().size() > 1) {
                for (int i = 1; i < classScheduleDto.getAttendTimes().size(); i++) {
                    //获取第n次添加时间结束时间 （第一次）
                    Object o = classScheduleDto.getAttendTimes().get(i - 1);
                    long scheduleEndTime = getScheduleEndTime(o);
                    //获取第n+1次添加时间开始时间
                    Object o1 = classScheduleDto.getAttendTimes().get(i);
                    long scheduleStartTime = getScheduleStartTime(o1);
                    //比较第n+1次开始时间和n次得结束时间
                    if (scheduleStartTime <= scheduleEndTime) {
                        throw new BizException(ApiResultCode.NO_LATER_THAN_LAST_TIME);
                    }
                }
            }
            //删除原始上课时间
            classOrActivityMapper.deleteClassSchedule(classScheduleDto);
            String s = JSON.toJSONString(classScheduleDto.getAttendTimes());
            classScheduleDto.setAttendTime(s);
            classOrActivityMapper.insertClassSchedule(classScheduleDto);
        }
        //课程时间重复
        else {
            if (classScheduleDto.getSourceWeek() == classScheduleDto.getWeek()) {
                if (classScheduleDto.getAttendTimes().size() > 1) {
                    for (int i = 1; i < classScheduleDto.getAttendTimes().size(); i++) {
                        //获取第n次添加时间结束时间 （第一次）
                        Object o = classScheduleDto.getAttendTimes().get(i - 1);
                        long scheduleEndTime = getScheduleEndTime(o);
                        //获取第n+1次添加时间开始时间
                        Object o1 = classScheduleDto.getAttendTimes().get(i);
                        long scheduleStartTime = getScheduleStartTime(o1);
                        //比较第n+1次开始时间和n次得结束时间
                        if (scheduleStartTime <= scheduleEndTime) {
                            throw new BizException(ApiResultCode.NO_LATER_THAN_LAST_TIME);
                        }
                    }
                }
                classOrActivityMapper.deleteClassSchedule(classScheduleDto);
                String s = JSON.toJSONString(classScheduleDto.getAttendTimes());
                classScheduleDto.setAttendTime(s);
                classOrActivityMapper.insertClassSchedule(classScheduleDto);
            } else {
                throw new BizException(ApiResultCode.SCHEDULE_EXIST);
            }
        }

    }

    /**
     * 删除上课时间
     **/
    public void deleteClassActivityTime(ClassSchedule classSchedule) {
        if (BizEmpty(commonUtils.getShopId(request))) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classSchedule.getClassOrActivityId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classSchedule.getWeek())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        ClassScheduleDto classScheduleDto = new ClassScheduleDto();
        classScheduleDto.setSourceWeek(classSchedule.getWeek());
        classScheduleDto.setClassOrActivityId(classSchedule.getClassOrActivityId());
        classOrActivityMapper.deleteClassSchedule(classScheduleDto);

    }

    public void updateClassActivity(ClassOrActivity classOrActivity) {//参数：课程id，商家id
        if (BizEmpty(classOrActivity.getId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getClassAddress())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getClassName())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getLongitude())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getLatitude())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getScope())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getLabel())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getImage())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getInventory())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getClassifyGoodsId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getStartTime())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getEndTime())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getIsSell())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(classOrActivity.getIsParent())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (commonUtils.getShopId(request) == null) {
            throw new BizException(ApiResultCode.FLAG_FAIL_VOUCHER);
        }
        classOrActivity.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        if (classOrActivity.getIsParent() == 1 && classOrActivity.getClassPid() == classOrActivity.getId()) {
            throw new BizException(ApiResultCode.CLASS_PID_NO_SELF);
        } else {
            classOrActivityMapper.updateClassOrActivity(classOrActivity);
        }


    }

    public void deleteClassActivity(Ids ids) {//参数：课程id、商家id
        if (BizEmpty(ids.getId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (commonUtils.getShopId(request) == null) {
            throw new BizException(ApiResultCode.FLAG_FAIL_VOUCHER);
        }
        List<ClassOrActivity> classOrActivities = classOrActivityMapper.selectInfoByClassId(ids);
        if (classOrActivities.size() > 0) {
            throw new BizException(ApiResultCode.PARENT_CLASS);
        }
        classOrActivityMapper.deleteClassOrActivity(ids);
        classOrActivityMapper.deleteClassSchedules(ids);
        classOrActivityMapper.deleteBindTeacherShop(ids);
    }

    private Map<String, Object> getClassMaterials(Integer id){
        LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<>();
        //查询课程教材
        ClassMaterials classMaterials = expandMapper.selectClassMaterials(id);
        if (classMaterials != null){
            JSONArray objects = JSON.parseArray(classMaterials.getImage());
            linkedHashMap.put("text",classMaterials.getText());
            linkedHashMap.put("images",objects);
        }
        return linkedHashMap;
    }
    private List<String> getClassOutline(Integer id) {
        ArrayList<String> list = new ArrayList<>();
        //查询教学大纲
        List<ClassOutline> classOutlines = expandMapper.selectOutlineList(id);
        if (classOutlines.size() > 0) {
            for (ClassOutline classOutline : classOutlines) {
                list.add(classOutline.getText());
            }
        }
        return list;
    }
    private List<Object> getClassProgress(Integer id){
        ArrayList<Object> list = new ArrayList<>();
        //查询教学进度
        List<ClassProgress> classProgresses = expandMapper.selectClassProgressList(id);
        if (classProgresses.size()>0){
            for (ClassProgress classProgress : classProgresses) {
                HashMap<String, Object> map = new HashMap<>();
                int stringTimestamp = Integer.parseInt(getStringTimestamp(getNowDateTime()));//当前时间戳
                String end_time = classProgress.getEndTime();
                int stringTimestamp1 = Integer.parseInt(getStringTimestamp(end_time));//上课结束时间戳
                if (stringTimestamp >stringTimestamp1){
                    map.put("flag","0");//0:已结束 1:未开始
                }else {
                    map.put("flag","1");
                }
                map.put("title",classProgress.getTitle());
                map.put("outline",classProgress.getOutline());
                map.put("start_time",classProgress.getStartTime());
                map.put("end_time",classProgress.getEndTime());
                list.add(map);
            }
        }
        return list;
    }
}
